import config from "./config";
import role from "./role";
const { sendKey , mKey } = config;
export default class Common {
  _gameMessage = JSON.parse(JSON.stringify(config.gameMessage));
  pageContext = null;
  _ownGameMessage = {}; // 自己游戏数据
  loadingText = null;
  netHost = '0';

  constructor(parameters) {
    this.pageContext = parameters;
  }

  get gameMessage() {
    return this._gameMessage;
  }
 
  set gameMessage(value) {
    this._gameMessage = value;
    if (this.pageContext && this.pageContext.setData) {
      const { count, userCount, lineCount, liveCount } = this.computedCount();
      this.pageContext.setData({ gameMessage: value, count, userCount, lineCount, liveCount });
    }
  }

  get ownGameMessage() {
    return this.pageContext.data.ownGameMessage ||  this._ownGameMessage;
  }

  set ownGameMessage(value) {
    this._ownGameMessage = value;
    // 更新页面数据
    if (this.pageContext && this.pageContext.setData) {
      this.pageContext.setData({ ownGameMessage: value });
    }
  }
    // 检查是否是重复消息
  _isDuplicateMessage(message) {
    if (!message[mKey.messageId] && !message[mKey.backMessageTryId]) {
      return false;
    }
    // 消息id
    if (message[mKey.messageId] && this.messageQueue.includes(message[mKey.messageId])) {
      return true;
    }else{
      message[mKey.messageId] && this.messageQueue.push(message[mKey.messageId]);
    }
    // 返回的id
    if (message[mKey.backMessageTryId] && this.messageQueue.includes(message[mKey.backMessageTryId])) {
      return true;
    }else{
      message[mKey.backMessageTryId] && this.messageQueue.push(message[mKey.backMessageTryId]);
    }
    // 保持队列在合理大小
    if (this.messageQueue.length > 1000) {
      this.messageQueue.shift();
    }
    return false;
  }
  
  // 计算人数
  computedCount() {
    const count = this.gameMessage.players.length;
    const userCount = this.gameMessage.players.filter(d => d.ip).length;
    const lineCount = this.gameMessage.players.filter(d => d.isLine && d.ip).length;
    const liveCount = this.gameMessage.players.filter(d => d.isLive && d.ip).length;
    return { count, userCount, lineCount, liveCount }
  }
  // 设置房间选择的 所有角色和数量
  setRoleAndCount() {
    const roleAndCount = [];
    const players = JSON.parse(JSON.stringify(this.gameMessage.players));
    let   { hasWolf, hasWitch, hasGuard, hasProphet } = this.pageContext.data;
    players.forEach((element) => {
      const index = roleAndCount.findIndex(d => d.name === element.name);
      if (index !== -1) {
        roleAndCount[index].number = roleAndCount[index].number + 1;
      }else{
        roleAndCount.push({
          name: element.name,
          number: 1,
        });
      }
      if(element.code === 7){
        hasWolf = true;
      }
      if(element.code === 5){
        hasWitch = true;
      }
      if(element.code === 3){
        hasGuard = true;
      }
      if(element.code === 4){
        hasProphet = true;
      }
    });
    this.pageContext.setData({ roleAndCount, hasWolf, hasWitch, hasGuard, hasProphet });
  }
  // 计算版本
  computedVersion(){
    if(this.gameMessage.version === 99){
       this.gameMessage.version = 0
    } else {
       this.gameMessage.version++
    }
    this.gameMessage = this.gameMessage
    return this.gameMessage.version
  }
  // 生成消息ID
  generateMessageId() {
    return `${Date.now().toString().slice(-4)}-${Math.random().toString(36).substr(2, 6)}`;
  }

  // 设置人员 在线
  setPartOnLine(ip) {
    this.gameMessage.players.forEach((element) => {
      if (element.ip === ip) {
        element.isLine = true;
      }
    });
    this.gameMessage = this.gameMessage;
  }

  // 设置人员 离线
  setPartOffLine(ip) {
    this.gameMessage.players.forEach((element) => {
      if (element.ip === ip) {
        element.isLine = false;
      }
    });
    this.gameMessage = this.gameMessage;
  }

  // 设置人员 淘汰
  setPartOffLive(ip) {
    this.gameMessage.players.forEach((element) => {
      if (element.ip === ip) {
        if(element.code === 6 && this.gameMessage.gameState === 6){
          element.out = true;
          element.isLive = true;
        } else {
          element.isLive = false;
        }
      }
    });
    this.gameMessage = this.gameMessage;
  }

  // 获取指定人员
  getAssignPart(ip) {
    const players = this.gameMessage.players;
    const index = players.findIndex(
      (element) => element.ip === ip && element.ip
    );
    return index == -1
      ? { index: -1, element: null }
      : { index, element: players[index] };
  }
  
  // 设置淘汰的人
  setKnockOut(knock = []){
    const knockOut = []
    knock.forEach(ip => {
      const { element, index } = this.getAssignPart(ip)
      if(element){
        this.setPartOffLive(ip)
        knockOut.push(element)
      }
    })
    this.pageContext.setData({ knockOut })
    this.gameMessage.knockOut = knock
    this.gameMessage = this.gameMessage
  }

  // 压缩投票数据
  gameVoteCompress(gameVoteCollect){
    const obj = {}
    gameVoteCollect.forEach((element) => {
      const votes = element.votes.map((item) => {
        return item.ip;
      });
      // 只保留有票数的玩家
      if(votes.length){
        obj[element.ip] = votes
      }
    });
    return obj
  }

  // 解压投票数据
  gameVoteExtract(arr){
    const extract = []
    Object.keys(arr).forEach((key) => {
      const { element, index } = this.getAssignPart(key)
      if(element){
        const newElement = JSON.parse(JSON.stringify(element))
        newElement.votes = []
        newElement.index =  index + 1
        arr[key].forEach((ip) => {
          const { element:children, index:childrenIndex } = this.getAssignPart(ip)
          if(children){
            const newChildren = JSON.parse(JSON.stringify(children))
            newChildren.index = childrenIndex + 1
            newElement.votes.push(newChildren)
          }
        });
       extract.push(newElement);
      }
    });
    return extract
  }

  // 设置可被投人员--- 进行击杀投票等
  setCanGameVote(){
    // 狼
    if(this.gameMessage.gameState === 1){
      const canGameVote = this.gameMessage.players.filter(d => d.isLive)
      this.pageContext.setData({ canGameVote })
    }
    // 巫
    if(this.gameMessage.gameState === 2){
      const canGameVote = this.gameMessage.players.filter(d => d.isLive)
      this.pageContext.setData({ canGameVote })
    }
    // 验
    if(this.gameMessage.gameState === 3){
      const canGameVote = this.gameMessage.players.filter(d => d.isLive && !d.out)
      this.pageContext.setData({ canGameVote })
    }
    // 守
    if(this.gameMessage.gameState === 4){
      const canGameVote = this.gameMessage.players.filter(d => d.isLive)
      this.pageContext.setData({ canGameVote })
    }
    // 猎
    if(this.gameMessage.gameState === 5){
      const canGameVote = this.gameMessage.players.filter(d => d.isLive && d.ip !== this.ownGameMessage.ip)
      this.pageContext.setData({ canGameVote })
    }
    // 投
    if(this.gameMessage.gameState === 105){
      const canGameVote = this.gameMessage.players.filter(d => d.isLive && !d.out)
      this.pageContext.setData({ canGameVote })
    }
  }

      // 获取角色信息
  getRoleMessage(code) {
    return role.find((element) => element.code === code) || {};
  }

  // 设置指定人可以操作（code）
  setCodeOperated(code){
    this.gameMessage.players.forEach( (item) => {
      if(item && item.ip && item.code === code){
        this.setPartOperated(item.ip)
      }
    })
  }

  // 设置指定人员可以操作
  setPartOperated(ip,type = 1) {
    this.gameMessage.players = this.gameMessage.players.map((element) => {
      if (element.ip === ip) {
        element.operated = type;
      }
      return element;
    });
    this.gameMessage = this.gameMessage;
    if(this.ownGameMessage.ip === ip){
      const ownGameMessage = this.ownGameMessage;
      ownGameMessage.operated = type;
      this.ownGameMessage = ownGameMessage;
      this.pageContext.setData({ operated: type })
    }
  }

  // 允许活着的人投票
  livePermitOperated(){
    this.gameMessage.players.forEach( (item) => {
       if(item && item.ip && item.isLive && !item.out){
        this.setPartOperated(item.ip)      
       }
    })
  }

  // 所有人是否完成操作
  allOperatedOk(){
    const isLiveOk = this.gameMessage.players.filter(d => d.isLive);
    const operatedOk = this.gameMessage.players.filter(d => d.operated === 2 || d.operated === 3);
    return isLiveOk.length === operatedOk.length;
  }
  
  // 计算进度条时间
  computedProgressTime(typeTime,pastTime,total){
    console.log('演示',Date.now() - pastTime)
    console.log('总',total)
    console.log('总',total)
    // typeTime
    // 狼开头 2150
    // 巫开头 2070
    // 守开头 2148
    // 预开头 2261
    const delay = Date.now() - pastTime;
    const progressTime = ((total * 1000) + (100 * total) + typeTime + 1100);
    const progressPercent = (1 - (delay / progressTime)) * 100
    // const time = (total * 1000) - (Date.now() - pastTime) + (100 * total) + typeTime + 1100;
    // this.pageContext.setData({progressTime,progressPercent:progressPercent.toFixed(0)})
    this.pageContext.setData({progressTime:progressTime / 1000,progressPercent:progressPercent.toFixed(2)})
  }
  // 判断游戏是否结束
  getOverState(outs = []) {
    const { goodCount, badCount } = this.gameMessage.players
      .filter((d) => d.isLive && !d.out && !outs.includes(d.ip)).reduce((acc, element) => {
          if (element.good) {
            acc.goodCount++;
          } else {
            acc.badCount++;
          }
          return acc;
        },
        { goodCount: 0, badCount: 0 }
      );
    // 0继续   1好人胜利   2坏人赢   3狼人和好人人数相等  在投票之后的结算狼人胜利
    return badCount === 0  ? 1 : badCount > goodCount ? 2 : badCount === goodCount ? 3 : 0;
  }

  // 关闭
  closeGameState() {
    this.pageContext.setData({ modalCole: 0, gameStateCard: 0 });
  }
  // 选择确定
  selectOk() {
    const element = this.pageContext.data.selectObj;
    if(!element.ip){
      wx.showToast({
        title: '请先选择人员',
        icon: 'none',
      });
      return;
    }
    // 投票
    if (this.gameMessage.gameState === 105) {
      this.voteClick(element);
      return;
    }
    // pk 重新投票
    if (this.gameMessage.gameState === 106) {
      this.voteClick(element);
      return;
    }
    // 狼人
    if (this.gameMessage.gameState === 1) {
      this.wolfClick(element);
      return;
    }
    // 守卫
    if (this.gameMessage.gameState === 4) {
      this.guardClick(element);
      return;
    }
    // 女巫技能
    if (this.gameMessage.gameState === 2 && this.pageContext.data.witchtype === 1) {
      this.witchKillClick(element);
      return;
    }
    if (this.gameMessage.gameState === 2 && this.pageContext.data.witchtype === 2) {
      this.witchSaveClick(element);
      return;
    }
    // 预言家技能
    if (this.gameMessage.gameState === 3) {
      this.prophetClick(element);
      return;
    }
    // 猎人技能
    if (this.gameMessage.gameState === 5) {
      this.hunterClick(element);
      return;
    }
  }
  // 放弃
  giveUpOk() {
    if (this.gameMessage.participateIn && this.isServer) {
      this.setPartOperated(this.gameMessage.gameIp,3)
      this.commonOnMessage({
        [mKey.backMessageType]: sendKey.giveUp_go,
      });
    } else {
      this.send({
        [mKey.messageType]: sendKey.giveUp_go,
        [mKey.loadingText]: "操作中...",
        [mKey.errorMessage]: "操作失败",
      });
    }
  }
  // 猎人放弃带走
  giveUpHunterOk(){
    if (this.gameMessage.participateIn && this.isServer) {
      this.setPartOperated(this.gameMessage.gameIp,3)
      this.hunterGiveUpSettlement();
    } else {
      this.send({
        [mKey.messageType]: sendKey.giveUp_go_hunter,
        [mKey.loadingText]: "操作中...",
        [mKey.errorMessage]: "操作失败",
      });
    }
  }

  // 狼人点击
  wolfClick(element) {
    if (this.gameMessage.participateIn && this.isServer) {
      this.setWolfKill(element);
      this.commonOnMessage({
        [mKey.backMessageType]: sendKey.wolf_kill,
        [mKey.userIp]: element.ip,
      });
    } else {
      this.send({
        [mKey.messageType]: sendKey.wolf_kill,
        [mKey.userIp]: element.ip,
        [mKey.loadingText]: "操作中...",
        [mKey.errorMessage]: "操作失败",
      });
    }
  }
  // 女巫点击--杀
  witchKillClick(element) {
    if (this.gameMessage.participateIn && this.isServer) {
      this.setWitchKill(element);
      this.commonOnMessage({
        [mKey.backMessageType]: sendKey.witch_kill,
        [mKey.userIp]: element.ip,
      });
    } else {
      this.send({
        [mKey.messageType]: sendKey.witch_kill,
        [mKey.userIp]: element.ip,
        [mKey.loadingText]: "操作中...",
        [mKey.errorMessage]: "操作失败",
      });
    }
  }
  // 女巫点击--救
  witchSaveClick(element) {
    if (this.gameMessage.participateIn && this.isServer) {
      this.setWitchSave(element);
      this.commonOnMessage({
        [mKey.backMessageType]: sendKey.witch_save,
        [mKey.userIp]: element.ip,
      });
    } else {
      this.send({
        [mKey.messageType]: sendKey.witch_save,
        [mKey.userIp]: element.ip,
        [mKey.loadingText]: "操作中...",
        errorMessage: "操作失败",
      });
    }
  }

  // 守卫点击
  guardClick(element) {
    if (this.gameMessage.participateIn && this.isServer) {
      this.setGuardPart(element);
      this.commonOnMessage({
        [mKey.backMessageType]: sendKey.guard_kill,
        [mKey.userIp]: element.ip,
      });
    } else {
      this.send({
        [mKey.messageType]:sendKey.guard_kill,
        [mKey.userIp]: element.ip,
        [mKey.loadingText]: "操作中...",
        [mKey.errorMessage]: "操作失败",
      });
    }
  }
  // 预言家点击
  prophetClick(element) {
    if (this.gameMessage.participateIn && this.isServer) {
      this.setProphetPart(element);
      this.commonOnMessage({
        [mKey.backMessageType]: sendKey.prophet_kill,
        [mKey.userIp]: element.ip,
      });
    } else {
      this.send({
        [mKey.messageType]: sendKey.prophet_kill,
        [mKey.userIp]: element.ip,
        [mKey.loadingText]: "操作中...",
        [mKey.errorMessage]: "操作失败",
      });
    }
  }

  // 猎人点击
  hunterClick(element) {
    if (this.gameMessage.participateIn && this.isServer) {
      this.setHunterPart(element);
      this.commonOnMessage({
        [mKey.backMessageType]: sendKey.hunter_kill,
        [mKey.userIp]: element.ip,
      });
    } else {
      this.send({
        [mKey.messageType]: sendKey.hunter_kill,
        [mKey.userIp]: element.ip,
        [mKey.loadingText]: "操作中...",
        [mKey.errorMessage]: "操作失败",
      });
    }
  }
  // 投票点击
  voteClick(element) {
    if (this.gameMessage.participateIn && this.isServer) {
      this.setVoteKill(element);
      this.commonOnMessage({
        [mKey.backMessageType]: sendKey.vote_kill,
        [mKey.userIp]: element.ip,
      });
    } else {
      this.send({
        [mKey.messageType]: sendKey.vote_kill,
        [mKey.userIp]: element.ip,
        [mKey.loadingText]: "操作中...",
        [mKey.errorMessage]: "操作失败",
      });
    }
  }
  // 历史数据-解压
  historyMessageExtract() {
      // d: this.gameMessage.day,
      // t: type,
      // k: this.gameMessage.knockOut,
      // g: this.gameMessage.gameVoteCollect,
    const history = []
    this.gameMessage.historyMessage.forEach(element => {
      const message = {}
      message.day = element.d
      message.dayState = element.s
      message.type = element.t
      message.knockOut = element.k.map(ip => {
        const { element:outElement } = this.getAssignPart(ip)
        return outElement
      })
      message.gameVoteCollect = this.gameVoteExtract(element.g)
      history.push(message)
    })
    this.pageContext.setData({
      historyMessage:history,
    });
  }
  
  // 设置历史数据 1、夜晚被杀记录 2.白天被杀记录 3.猎人操作记录 4.白痴被票出
  setHistoryMessage(type = 1) {
    const historyMessage = this.pageContext.data.historyMessage;
    const gameVoteCollect = JSON.parse(JSON.stringify(this.gameMessage.gameVoteCollect || {}))
    const knockOut = JSON.parse(JSON.stringify(this.gameMessage.knockOut || []))
    const pageKnockOut = knockOut.map(ip => {
      const { element:outElement } = this.getAssignPart(ip)
      return outElement
    })
    console.log(gameVoteCollect,this.gameVoteExtract(gameVoteCollect))
    historyMessage.unshift({
      day: this.gameMessage.day,
      dayState: this.gameMessage.dayState,
      type: type || 1,
      knockOut: pageKnockOut,
      gameVoteCollect: this.gameVoteExtract(gameVoteCollect),
    });
    console.log(historyMessage,'=========historyMessage======')
    this.pageContext.setData({
      historyMessage,
    });
    this.gameMessage.historyMessage.unshift({
      t: type || 1,
      s: this.gameMessage.dayState,
      d: this.gameMessage.day,
      k: knockOut,
      g: gameVoteCollect,
    })
    console.log(historyMessage,'=========historyMessage======')
  }
  
  // 收到消息
  commonOnMessage(message = {}) {
    if(Object.keys(message).length && !message[mKey.backMessageType]){
      console.log(message,'=====收commonOnMessage========')
    }

    // 再来一局
    if (message[mKey.messageType] === sendKey.reset_permit) {
      this.gameMessage.players.forEach(element => {
        element.isLive = true;
        element.out = false;
      });
      this.gameMessage.day = 1;
      this.gameMessage.dayState = 0;
      this.gameMessage.gameState = 200;
      this.gameMessage.historyMessage = [];
      this.gameMessage.gameStateMes = '请玩家准备';
      this.gameMessage.WKU = undefined; 
      this.gameMessage.GKU = undefined; 
      this.gameMessage.PKU = undefined,
      this.gameMessage.WIKU = undefined;
      this.gameMessage.WISU = undefined;
      this.gameMessage.HKU = undefined;
      this.gameMessage.gameVoteCollect = {};
      this.gameMessage.revoteCanVote = [];
      this.gameMessage.knockOut = [];
      this.gameMessage.witchSave = true;
      this.gameMessage.witchKill = true;
      this.pageContext.setData({
        gameStateCard: 0, 
        modalCole: 0,
        selectObj: {},
        witchtype: 0, // 1毒 2救
        historyMessage: [],
        canGameVote:[],
        knockOut:[],
        operated: 0,
      })
      this.gameMessage = this.gameMessage;
    }

    // 游戏状态修改
    if (message[mKey.gameState]) {
      this.gameMessage.gameState = message[mKey.gameState];
      this.gameMessage = this.gameMessage
    }

    //有人加入游戏
    if (message[mKey.messageType] === sendKey.playerAdd) {
      const players = this.gameMessage.players;
      const hasIndex = players.findIndex(d => d.ip === message[mKey.userIp])
      if(hasIndex !== -1 ){
        players[hasIndex].isLine = true
      }else{
        for (let element of players) {
          if (!element.ip) {
            element.isLine = true;
            element.userPicture = message[mKey.userPicture];
            element.userName = message[mKey.userName];
            element.ip = message[mKey.userIp];
            break;
          }
        }
      }
      this.gameMessage.players = players;
      this.gameMessage = this.gameMessage
    }
    
    // 收到有人退出
    if (message[mKey.messageType] === sendKey.exit) {
        const players = this.gameMessage.players;
        players.forEach((element) => {
          if (element.ip === message[mKey.userIp]) {
            element.isLine = false;
            element.ip = null;
            element.userName = null;
            element.userPicture = null;
          }
        });
        this.gameMessage.players = players;
        this.gameMessage = this.gameMessage
    }

    // 收到更新用户信息
    if (message[mKey.messageType] === sendKey.updataUser) {
        const players = this.gameMessage.players;
        players.forEach((element) => {
          if (element.ip === message[mKey.userIp]) {
            element.userName = message[mKey.userName];
            element.userPicture = message[mKey.userPicture];
          }
        });
        this.gameMessage.players = players;
        this.gameMessage = this.gameMessage
    }

    // 收到角色分配
    if (message[mKey.messageType] === sendKey.issuePart) {
      this.gameMessage.gameState = 201
      this.gameMessage.gameStateMes = `确认身份`
      this.gameMessage.players = this.gameMessage.players.map((element, index) => {
        const gameObj = this.getRoleMessage(message[mKey.codeList][index])
        element = {
          ...gameObj,
          ip:element.ip,
          userName: element.userName,
          userPicture: element.userPicture,
        }
        return element
      });
      this.gameMessage = this.gameMessage
      const { element: ownGameMessage } = this.getAssignPart(this.ownGameMessage.ip)
      if(ownGameMessage){
        this.ownGameMessage = JSON.parse(JSON.stringify(ownGameMessage))
        this.pageContext.setData({ modalCole: 17 });
      }
    }

    // 投票成功
    if (message[mKey.backMessageType] === sendKey.vote_kill) {
      this.gameMessage.gameStateMes = `等待法官公布结果`
      this.gameMessage = this.gameMessage
      this.pageContext.setData({ gameStateCard:0, operated: 2,selectObj:{} });
      wx.showToast({ title: "操作成功", icon: "none" });
    }

    // 狼杀成功
    if (message[mKey.backMessageType] === sendKey.wolf_kill) {
      this.pageContext.setData({ gameStateCard:0, operated: 2,selectObj:{} });
      wx.showToast({ title: "操作成功", icon: "none" });
    }

    // 巫杀成功
    if (message[mKey.backMessageType] === sendKey.witch_kill) {
      this.pageContext.setData({ gameStateCard:0, operated: 2,selectObj:{},witchtype:0 });
      wx.showToast({ title: "操作成功", icon: "none" });
    }

    // 巫救成功
    if (message[mKey.backMessageType] === sendKey.witch_save) {
      this.pageContext.setData({ gameStateCard:0, operated: 2,selectObj:{},witchtype:0 });
      wx.showToast({ title: "操作成功", icon: "none" });
    }

    // 预言家成功
    if (message[mKey.backMessageType] === sendKey.prophet_kill) {
      this.pageContext.setData({ gameStateCard:0, operated: 2, modalCole: 10 });
      // wx.showToast({ title: "操作成功", icon: "none" });
    }

    // 守护成功
    if (message[mKey.backMessageType] === sendKey.guard_kill) {
      this.pageContext.setData({ gameStateCard:0, operated: 2,selectObj:{} });
      wx.showToast({ title: "操作成功", icon: "none" });
    }

    // 猎人带走成功
    if (message[mKey.backMessageType] === sendKey.hunter_kill) {
      this.pageContext.setData({ operated: 2, modalCole: 0,gameStateCard:0,selectObj:{} });
      wx.showToast({ title: "操作成功",icon:'none' });
    }

    // 放弃成功
    if (message[mKey.backMessageType] === sendKey.giveUp_go) {
      this.pageContext.setData({ gameStateCard:0, operated: 3, selectObj:{},witchtype: 0});
      if(this.gameMessage.gameState === 105 || this.gameMessage.gameState === 106){
        this.gameMessage.gameStateMes = `等待法官公布结果`
        this.gameMessage = this.gameMessage
      }
      wx.showToast({ title: "操作成功", icon: "none" });
    }

    // 猎人放弃成功
    if (message[mKey.backMessageType] === sendKey.giveUp_go_hunter) {
      this.pageContext.setData({ gameStateCard:0, operated: 3, modalCole: 0, selectObj:{}});
      wx.showToast({ title: "操作成功", icon: "none" });
    }

    // 猎人放弃操作提示
    if (message[mKey.messageType] === sendKey.hunter_giveUp) {
      this.pageContext.setData({ modalCole: 0,gameStateCard:0, selectObj:{} });
      if(this.gameMessage.WKU){
        // 狼杀的猎
        this.gameMessage.gameState = 502
        this.gameMessage.gameStateMes = `猎人放弃操作`
      }else{
        // 驱逐的猎
        this.gameMessage.gameState = 503
        this.gameMessage.gameStateMes = `猎人放弃操作`
      }

      if(this.ownGameMessage.code !== 2){
        if (!this.ownGameMessage.isLive) return;
        this.pageContext.setData({ modalCole: 38 });
      }
      this.gameMessage = this.gameMessage
    }

    // 天黑了 禁止操作
    if (message[mKey.messageType] === sendKey.ban_permit) {
      this.gameMessage.gameState = 0;
      this.gameMessage.gameStateMes = `请闭眼`
      this.gameMessage.dayState = 0; // 黑夜
      this.gameMessage.players.forEach(element => {
        element.operated = 0;
      })
      this.gameMessage = this.gameMessage
      this.pageContext.setData({ modalCole: 0, selectObj: {}, operated: 0,gameStateCard:0 });
    }

    // 收到闭眼
    if (message[mKey.messageType] === sendKey.closeEyes) {
      this.gameMessage.gameStateMes = `请闭眼`
      this.gameMessage.players.forEach(element => {
        element.operated = 0;
      })
      this.gameMessage = this.gameMessage
      this.pageContext.setData({ modalCole: 0, selectObj: {}, operated: 0,gameStateCard:0 });
    }

    // 收到开始投票
    if (message[mKey.messageType] === sendKey.vote_permit) {
      this.gameMessage.gameState = 105;
      this.gameMessage.gameStateMes = `投票`
      this.gameMessage = this.gameMessage
      if (!this.ownGameMessage.isLive || this.ownGameMessage.out) return;
      // 允许操作
      this.livePermitOperated()
      this.setCanGameVote()
      this.pageContext.setData({ operated: 1, gameStateCard:105 });
    }

    // 狼收开始操作
    if (message[mKey.messageType] === sendKey.wolf_permit) {
      this.setCodeOperated(7)
      this.gameMessage.gameState = 1;
      this.gameMessage.gameStateMes = `狼人睁眼`
      this.gameMessage = this.gameMessage
      if (!this.ownGameMessage.isLive || this.ownGameMessage.code !== 7) return;
      this.setCanGameVote()
      this.computedProgressTime(2150,message[mKey.sendTime],message[mKey.progressTime])
      this.pageContext.setData({ gameStateCard: 1 })
    }

    // 女巫收
    if (message[mKey.messageType] === sendKey.witch_permit) {
      this.setCodeOperated(5)
      this.gameMessage.gameState = 2;
      this.gameMessage.gameStateMes = `女巫睁眼`
      this.gameMessage = this.gameMessage
      if (!this.ownGameMessage.isLive || this.ownGameMessage.code !== 5) return;
      this.computedProgressTime(2070,message[mKey.sendTime],message[mKey.progressTime])
      this.setCanGameVote()
      const { element:WKUElement } = this.getAssignPart(message[mKey.WKU]);
      this.gameMessage.WKU = message[mKey.WKU]
      this.gameMessage.witchKill = message[mKey.witchKill]
      this.gameMessage.witchSave = message[mKey.witchSave]
      this.gameMessage = this.gameMessage
      // 技能操作
      if(WKUElement && message[mKey.witchSave]){
        this.pageContext.setData({ gameStateCard: 2, witchtype: 2, canGameVote:[WKUElement] }) // 救
      }else{
        if(message[mKey.witchKill]){
          this.pageContext.setData({ gameStateCard: 2, witchtype: 1 }) // 毒
        }else{
          this.pageContext.setData({ operated: 0, modalCole: 41, gameStateCard: 0, witchtype: 0 }) // 毒
        }
      }
    }

    // 预言家收
    if (message[mKey.messageType] === sendKey.prophet_permit) {
      this.setCodeOperated(4)
      this.gameMessage.gameState = 3;
      this.gameMessage.gameStateMes = `预言家查验`
      this.gameMessage = this.gameMessage
      if (!this.ownGameMessage.isLive  || this.ownGameMessage.code !== 4) return;
      this.computedProgressTime(2261,message[mKey.sendTime],message[mKey.progressTime])
      this.setCanGameVote()
      this.pageContext.setData({ gameStateCard: 3 })
    }

    // 守卫收
    if (message[mKey.messageType] === sendKey.guard_permit) {
      this.setCodeOperated(3)
      this.gameMessage.gameState = 4;
      this.gameMessage.gameStateMes = `守卫保护`
      this.gameMessage = this.gameMessage
      if (!this.ownGameMessage.isLive || this.ownGameMessage.code !== 3) return;
      this.computedProgressTime(2148,message[mKey.sendTime],message[mKey.progressTime])
      this.setCanGameVote()
      this.pageContext.setData({ gameStateCard: 4 })
    }

    // 猎人收（被票出）---其他玩家也提示
    if (message[mKey.messageType] === sendKey.hunter_permit) {
      this.setCodeOperated(2)
      this.gameMessage.gameState = 5;
      this.gameMessage.gameStateMes = `猎人带人`
      this.setKnockOut(message[mKey.knockOut])
      this.gameMessage.gameVoteCollect = message[mKey.gameVoteCollect]
      this.gameMessage = this.gameMessage
      this.setHistoryMessage(message[mKey.type])
      // 狼人杀的猎人
      if(this.gameMessage.WKU){
        this.gameMessage.dayState = 1;
        this.gameMessage.day = this.gameMessage.day + 1; //每天递增
        this.gameMessage = this.gameMessage
      }
      const isMeOut = message[mKey.knockOut].find(
        (ip) => ip === this.ownGameMessage.ip && this.ownGameMessage.code === 2
      );
      if (isMeOut) {
        this.ownGameMessage.isLive = false
        this.ownGameMessage = this.ownGameMessage
        this.setCanGameVote()
        if(message[mKey.knockOut].length > 1){
          // 多人
          this.pageContext.setData({ modalCole: 40, gameStateCard:0 })
        }else{
          // 自己
          this.pageContext.setData({ modalCole: 13, gameStateCard:0 })
        }
      } else {
      if (!this.ownGameMessage.isLive) return;
        // 临时提示
        if(message[mKey.knockOut].length > 1){
          // 多人
          this.pageContext.setData({ modalCole: 39, gameStateCard:0 })
        }else{
          // 一个人
          const { element:elementKnockOut } = this.getAssignPart(message[mKey.knockOut][0]);
          this.pageContext.setData({ modalCole: 11,gameStateCard:0,knockOut:[elementKnockOut] });
        }
      }
    }

    // 昨夜谁死了--被杀人提示
    if (message[mKey.messageType] === sendKey.knockOut) {
      const out = [];
      let user = ''
      message[mKey.knockOut].map((ip,i) => {
          this.setPartOffLive(ip);
          const { element } = this.getAssignPart(ip);
          const have = out.find((d) => d.ip === ip);
          !have && out.push(element);
          user = i == 0 ? user + element.userName : user + '、' + element.userName
      });
      this.gameMessage.gameState = 104
      this.gameMessage.gameStateMes = `昨夜【${user}】被杀死`
      this.gameMessage.WKU == message[mKey.knockOut][0];
      this.setKnockOut(message[mKey.knockOut])
      this.gameMessage = this.gameMessage
      this.setCanGameVote()
      this.setHistoryMessage(1)
      this.gameMessage.dayState = 1;
      this.gameMessage.day = this.gameMessage.day + 1; //每天递增
      this.gameMessage = this.gameMessage
      const isMeOut = out.find(
        (outElement) => outElement.ip === this.ownGameMessage.ip
      );

      if (isMeOut && out.length === 1) {
        this.ownGameMessage.isLive = false
        this.ownGameMessage = this.ownGameMessage
        // 提示自己被杀
        this.pageContext.setData({
          modalCole: 14,
        });
      } else if (isMeOut && out.length !== 1) {
        this.ownGameMessage.isLive = false
        this.ownGameMessage = this.ownGameMessage
        // 提示自己和别人被杀
        this.pageContext.setData({
          modalCole: 12,
        });
      } else {
        if(!this.ownGameMessage.isLive) return;
        // 提示别人被杀
        this.pageContext.setData({
          modalCole: 12,
        });
      }
    }

    // 猎人带走某人提示  
    if (message[mKey.messageType] === sendKey.hunter_kill_end) {
      const key = this.gameMessage.knockOut[0]
      const { element:hunter } = this.getAssignPart(key);
      const { element } = this.getAssignPart(message[mKey.userIp]);
      this.gameMessage.gameStateMes = `${hunter.userName} 带走了 ${element.userName}`
      this.gameMessage.gameState = 501
      this.gameMessage = this.gameMessage
      // 添加到淘汰名单
      this.setKnockOut([key,message[mKey.userIp]])
      this.gameMessage.gameVoteCollect = {[message[mKey.userIp]]:[key]}
      this.setHistoryMessage(3)
      // const isMeOut = message[mKey.userIp] === this.ownGameMessage.ip
      this.setCanGameVote()
      if (!this.ownGameMessage.isLive) return;
      this.pageContext.setData({
          modalCole: 25,
      });
      // if (isMeOut) {
      //   // 提示自己被猎人带走了
      //   this.ownGameMessage.isLive = false
      //   this.ownGameMessage = this.ownGameMessage
      //   // 你被猎人带走了
      //   this.pageContext.setData({
      //     modalCole: 30,
      //   });
      // } else {
      //   if(this.gameMessage.WKU){
      //     // 狼杀的猎 （全部公布  狼杀+投票）
      //     this.pageContext.setData({
      //       modalCole: 12,
      //     });
      //   }else{
      //     // 投票的猎 （全部公布  狼杀+投票）
      //     this.pageContext.setData({
      //       modalCole: 23,
      //     });
      //   }
      // }
    }

    // 操作--平安夜
    if (message[mKey.messageType] === sendKey.safety) {
      this.setCanGameVote()
      this.gameMessage.gameStateMes = `平安夜`
      this.gameMessage.gameState = 104
      this.gameMessage.knockOut = [];
      this.gameMessage.gameVoteCollect = {};
      this.gameMessage = this.gameMessage
      this.setHistoryMessage(1)
      this.gameMessage.dayState = 1;
      this.gameMessage.day = this.gameMessage.day + 1; //每天递增
      this.gameMessage = this.gameMessage

      if (!this.ownGameMessage.isLive) return;
      this.pageContext.setData({
        modalCole: 20,
      });
    }

    // 收到重票再次投票
    if (message[mKey.messageType] === sendKey.revote_permit) {
      this.gameMessage.gameVoteCollect = {}
      this.gameMessage.gameState = 106;
      let user = ''
      const canGameVote = []
      message[mKey.revoteCanVote].forEach((ip,i) => {
        const { element } = this.getAssignPart(ip);
        if(element){
          user = i == 0 ? user + element.userName : user + '、' + element.userName
          canGameVote.push(element)
        }
      })
      this.gameMessage.gameStateMes = `PK【${user}】票数相同`
      this.gameMessage = this.gameMessage
      if (!this.ownGameMessage.isLive) return;
      this.pageContext.setData({ canGameVote });
      // 重新投票
      this.pageContext.setData({ operated: 1, gameStateCard: 106 })
    }

    // 被驱逐提示
    if (message[mKey.messageType] === sendKey.voteEnd) {
      // 同步玩家被淘汰
      this.gameMessage.WKU = undefined;
      const outUser = this.getAssignPart(message[mKey.userIp]) && this.getAssignPart(message[mKey.userIp]).element
      this.gameMessage.gameStateMes = outUser.code === 6 ? `【${outUser.userName}】被驱逐,身份白痴` : `【${outUser.userName}】被驱逐`
      this.gameMessage.gameState = outUser.code === 6 ? 6 : 107
      console.log('拍====',message[mKey.gameVoteCollect])
      console.log(999999,message[mKey.gameVoteCollect])
      this.gameMessage.gameVoteCollect = message[mKey.gameVoteCollect]
      this.gameMessage = this.gameMessage
      this.setKnockOut([message[mKey.userIp]])

      if(outUser.code === 6){
        // 白痴
        this.setHistoryMessage(4)
      }else{
        this.setHistoryMessage(2)
      }
     
      const isMeOut = message[mKey.userIp] === this.ownGameMessage.ip
       this.gameMessage = this.gameMessage
      if (!!isMeOut) {
        // 并且自己不是白痴
        if(outUser.code !== 6){
          this.ownGameMessage.isLive = false
          this.ownGameMessage = this.ownGameMessage
          // 提示自己被驱逐
          this.pageContext.setData({ modalCole: 22, gameStateCard: 0 });
        }else{
          this.ownGameMessage.out = true
          this.ownGameMessage = this.ownGameMessage
          this.pageContext.setData({ modalCole: 43, gameStateCard: 0 });
        }
      } else {
        // 提示别人被驱逐
        // 是否是白痴
        if (!this.ownGameMessage.isLive) return;
        if(outUser.code === 6){
          this.pageContext.setData({ modalCole: 36, gameStateCard: 0 });
        }else{
          this.pageContext.setData({ modalCole: 23, gameStateCard: 0 });
        }
      }
    }

    // 投票--无人投票
    if (message[mKey.messageType] === sendKey.noVote) {
      this.gameMessage.gameState = 107
      this.gameMessage.gameStateMes = '无人票出'
      this.gameMessage.knockOut = [];
      this.gameMessage.gameVoteCollect = {};
      this.gameMessage = this.gameMessage
      this.setHistoryMessage(2)
      if (!this.ownGameMessage.isLive) return;
      this.pageContext.setData({
        modalCole: 24,
        gameStateCard: 0,
      });
    }


    // 好人胜利
    if (message[mKey.messageType] === sendKey.server_good_win) {
      // 谁被淘汰
      this.setKnockOut(message[mKey.knockOut])
      this.gameMessage.gameState = 108;
      this.gameMessage.gameStateMes = '游戏结束，好人胜利'
      this.gameMessage = this.gameMessage
      this.pageContext.setData({ modalCole: 18,gameStateCard: 0  });
      // 投票结果
      if(message[mKey.gameVoteCollect]){
       this.gameMessage.gameVoteCollect =  message[mKey.gameVoteCollect] // 投票结果
       this.gameMessage = this.gameMessage
      }
      if(message[mKey.HKU]){
        this.gameMessage.gameVoteCollect = {[message[mKey.HKU]]:[message[mKey.knockOut][0]]}
        this.gameMessage = this.gameMessage
      }
      this.setHistoryMessage(message[mKey.type])
    }

    // 狼人胜利
    if (message[mKey.messageType] === sendKey.server_wolf_win) {
      this.setKnockOut(message[mKey.knockOut])
      this.gameMessage.gameState = 108;
      this.gameMessage.gameStateMes = '游戏结束，狼人胜利'
      this.gameMessage = this.gameMessage
      this.pageContext.setData({ modalCole: 19, gameStateCard: 0 });
      console.log('this.gameMessage',this.gameMessage)
      // 投票结果
      if(message[mKey.gameVoteCollect]){
        console.log('gameVoteCollect',message[mKey.gameVoteCollect])
       this.gameMessage.gameVoteCollect =  message[mKey.gameVoteCollect] // 投票结果
       this.gameMessage = this.gameMessage
      }
      if(message[mKey.HKU]){
        this.gameMessage.gameVoteCollect = {[message[mKey.HKU]]:[message[mKey.knockOut][0]]}
        this.gameMessage = this.gameMessage
      }
      this.setHistoryMessage(message[mKey.type])
    }
  }
}
